<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
  <link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
  <script src='https://vjs.zencdn.net/7.4.1/video.js'></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.15.0/videojs-contrib-hls.min.js"></script>
</head>

<body>
  <video id="video" width="640" height="360" controls></video>
  <button id="download" style="padding: 10px 20px;">下载</button>
  <script>
    async function downloadM3U8(m3u8Url, cb) {
      try {
        // 获取m3u8文件内容
        const m3u8Response = await fetch(m3u8Url);
        const m3u8Text = await m3u8Response.text();

        // 解析m3u8文件获取所有.ts文件的URL
        const tsUrls = m3u8Text.match(/[^\s\r\n]+\.ts(\?[^\s\r\n]*)?/g)
          .map(tsPath => {
            // 如果是完整URL，直接返回
            if (tsPath.startsWith('http')) {
              return tsPath;
            }
            // 如果是相对路径，需要根据基础URL构建完整URL
            const baseUrl = m3u8Url.substring(0, m3u8Url.lastIndexOf('/') + 1);
            return baseUrl + tsPath;
          });

        // 并行下载所有的.ts文件
        const tsBlobs = await Promise.all(tsUrls.map(url =>
          fetch(url).then(res => res.blob())
        ));

        // 合并所有的.ts文件
        const chunks = [];
        for (const blob of tsBlobs) {
          const arrayBuffer = await blob.arrayBuffer();
          chunks.push(arrayBuffer);
        }

        // 创建合并后的Blob
        const videoBlob = new Blob(chunks, { type: 'video/MP4' });

        // 创建下载链接
        const url = URL.createObjectURL(videoBlob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'm3u8_video.mp4';
        document.body.appendChild(a);
        a.click();

        // 清理
        // URL.revokeObjectURL(url);
        // document.body.removeChild(a);
        cb(url)
      } catch (err) {
        console.error('下载失败:', err);
      }
    }
  </script>
  <script>
    var videoUrl = 'https://m.media-amazon.com/images/S/vse-vms-transcoding-artifact-us-east-1-prod/bda11534-a8e7-4366-a39a-a88c48817c27/default.jobtemplate.hls360.m3u8';
    // var videoUrl = 'https://vod3.cf.dmcdn.net/sec2(eCZ4WpOWEF3hXMj7d9TbcMeJalFkKEOYr9rQdHBUJrEcZSkqhoAdgeQj2WDgXpD6kezmjO0Eymj1K35fAPqy3JlhwUVATjDgN6wwDVz_uh-9TMdz-KUlc9l-Wrzr7aPi9V3DvYrAmfCG_M1LHzmT8-bhE0xLbGOB8HJ-sCZ-BOB03natGFqdSTrVpadXXu6Q)/video/029/186/556681920_mp4_h264_aac_hq_1.m3u8';


    download.addEventListener('click', () => {
      downloadM3U8(videoUrl, (videoUrl) => {
        var hls = new Hls();
        hls.loadSource(videoUrl);
        hls.attachMedia(document.getElementById('video'));
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
          // video.muted = false;
          // video.play();
        });
      });

    });
  </script>
</body>

</html>